﻿using AutoMapper;
using DFGK_WMS.Context;
using DFGK_WMS.IRepository;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace DFGK_WMS.Repository
{
    /// <summary>
    /// 货主
    /// </summary>
    public class OwnerRepository: BaseRepository<TOwner>, IOwnerRepository
    {
        public OwnerRepository(DFGK_DB context, IMapper mapper) : base(context, mapper)
        {
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <returns></returns>
        public List<TOwner> Getowner()
        {
            return Context.TOwners.AsQueryable().ToList();
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public bool AddOwner(OwnerDto dto)
        {
            try
            {
                string code = "Owner";
                var aobj = Context.TOwners.AsNoTracking().Where(x => x.Code.Contains(code)).OrderByDescending(x => x.CreateDate).FirstOrDefault();
                if (aobj != null)
                {
                    string pattern = @"\d+";
                    MatchCollection matches = Regex.Matches(aobj.Code, pattern);
                    string value = matches[matches.Count - 1].Value;
                    int values = Convert.ToInt32(value);
                    values++;
                    dto.Code = code + values.ToString("D4");
                }
                else
                {
                    int i = 1;
                    dto.Code = code + i.ToString("D4");
                }

                TOwner own = new TOwner()
                {
                    Code = dto.Code,
                    Name = dto.Name,
                    AddrDetail = dto.AddrDetail,
                    ZipCode = dto.ZipCode,
                    Contacts = dto.Contacts,
                    MobilePhone = dto.MobilePhone,
                    Email = dto.Email,
                    Status = dto.Status,
                    Remark = dto.Remark,
                    CreateDate = DateTime.Now,
                    CreateUserId = dto.NowUserId,
                    CreateUserName = dto.NowUserRealName
                };
                Context.TOwners.Add(own);
                return Context.SaveChanges() > 0;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
